package IC.videopatrol.service.impl;


import IC.videopatrol.config.FaceConfig;
import IC.videopatrol.service.FaceRecognitionservice;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ic.domain.response.FaceDetectionResponse;
import com.ic.domain.response.FaceDetectionResponse2;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Log4j2
public class FaceRecognitionserviceImpl implements FaceRecognitionservice {
    @Autowired
    private RestTemplate restTemplate;

   @Autowired
   private FaceConfig faceConfig;



    @Override
    @Transactional
    public String recognizeFace(String imageBase64) throws IOException {
        // 创建JSON对象映射器
        ObjectMapper mapper = new ObjectMapper();

        // 创建请求体Map，包含键值对："file" -> imageBase64
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("file", imageBase64);

        // 将请求体序列化为JSON格式的字符串
        String jsonRequest = mapper.writeValueAsString(requestBody);

        // 构建API URL，其中SUBJECT_NAME需要在外部定义
        String apiUrl = faceConfig.getAPI_Url() + faceConfig.getSUBJECT_NAME();
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建HttpPost对象，设置URL
            HttpPost post = new HttpPost(apiUrl);

            // 设置请求头信息
            post.setHeader(faceConfig.getContent_Type(), faceConfig.getContent_Type_Value());
            post.setHeader(faceConfig.getX_api_key(), faceConfig.getBk_key_value());

            // 设置请求体，将JSON字符串作为请求的实体
            post.setEntity(new StringEntity(jsonRequest, StandardCharsets.UTF_8));

            // 执行POST请求，并捕获响应
            try (CloseableHttpResponse response = client.execute(post)) {
                // 将响应实体转换为字符串
                String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                // 打印响应内容
                System.out.println(responseString);

                // 返回响应字符串
                return responseString;
            }
        }
    }


    @Override
    public void deleteFaceBySubject(String subject) {
        String baseUrl = faceConfig.getBk_baseUrl();
        String methodAddr = faceConfig.getMethodAddr();
        String url = baseUrl + methodAddr + "?subject=" + subject;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("X-Api-Key", faceConfig.getImgContrastkey());

        HttpEntity<String> entity = new HttpEntity<>(headers);

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
            String responseBody = responseEntity.getBody();
            log.info("删除操作成功，结果为：" + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除操作异常：" + e.getMessage());
        }

    }

    @Override
    public void deleteFaceByImageId(String subject, String imageId) {
        String baseUrl = faceConfig.getBk_baseUrl();
        String methodAddr = faceConfig.getMethodAddr();
        String url = baseUrl + methodAddr + imageId;
        try {
            HttpHeaders deleteHeaders = new HttpHeaders();
            deleteHeaders.setContentType(MediaType.APPLICATION_JSON); // 假设API接受JSON格式的请求
            deleteHeaders.add("X-Api-Key", faceConfig.getImgContrastkey()); // 添加API密钥
            // 创建只包含subject的请求体
            String deleteBody = "{\"subject\": \"" + subject + "\"}";

            // 创建HttpEntity，包含请求体和请求头
            HttpEntity<String> deleteRequestEntity = new HttpEntity<>(deleteBody, deleteHeaders);

            // 发送DELETE请求
            ResponseEntity<String> deleteResponseEntity = restTemplate.exchange(url, HttpMethod.DELETE, deleteRequestEntity, String.class);

            // 获取响应体并打印
            String deleteResponseBody = deleteResponseEntity.getBody();
            System.out.println("Delete Response: " + deleteResponseBody);

            // 根据响应进行相应的处理
            if (deleteResponseEntity.getStatusCode().is2xxSuccessful()) {
                // 删除成功
                System.out.println("人脸删除成功");
            } else {
                // 删除失败，记录错误信息
                log.error("删除人脸失败：" + deleteResponseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除人脸时发生异常：" + e.getMessage());

        }

    }

    @Override
    public FaceDetectionResponse faceDetect(String imageBase64) throws IOException {
        FaceDetectionResponse faceDetectionResponse1 = null; // 声明变量在外部

        // 替换空格为加号并提取Base64编码的字符串
        String base64Image = imageBase64.replaceAll(" ", "+").split(",")[1];
        // 构建请求的URL
        String url = faceConfig.getUrl();

        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 准备请求体
            HashMap<String, Object> map = new HashMap<>();
            map.put("file", base64Image);

            StringEntity params = new StringEntity(new ObjectMapper().writeValueAsString(map), "UTF-8");
            httpPost.addHeader(faceConfig.getContent_Type(), faceConfig.getContent_Type_Value());
            httpPost.addHeader(faceConfig.getX_api_key(), faceConfig.getBk_key_value());
            httpPost.setEntity(params);

            // 发送HTTP请求
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                // 获取响应实体
                org.apache.http.HttpEntity entity = httpResponse.getEntity();
                String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                // 打印HTTP响应状态码
                System.out.println(httpResponse.getStatusLine().getStatusCode());

                // 读取响应内容

                System.out.println(json);
                // 使用Jackson来解析JSON
                ObjectMapper mapper = new ObjectMapper();
                faceDetectionResponse1 = mapper.readValue(json, FaceDetectionResponse.class);
                if (faceDetectionResponse1 != null && !faceDetectionResponse1.getResult().isEmpty()) {
                    System.out.println(faceDetectionResponse1.getResult().get(0)); // 打印第一个结果，或者处理整个列表
                } else {
                    System.out.println("No results found or faceDetectionResponse is null");
                }
                System.out.println(faceDetectionResponse1);
                // 输出结果
                if (faceDetectionResponse1 != null) {
                    System.out.println(faceDetectionResponse1.getResult());
                } else {
                    System.out.println("faceDetectionResponse is null");
                }
                // 确保HttpEntity的内容被完全消费
                EntityUtils.consume(entity);
            } catch (IOException e) {
                // 捕获并处理异常
                e.printStackTrace();
                throw new RuntimeException("Failed to parse JSON response", e);
            }
        }
        faceDetectionResponse1.getResult().forEach(result -> {
            result.getSubjects().forEach(subject -> {
                double similarity = subject.getSimilarity();
            });
        });

        // 返回解析后的对象
        return faceDetectionResponse1;

    }

    @Override
    public FaceDetectionResponse2 imgContrast(String imageBase64) throws IOException {
        String base64Image = imageBase64.replaceAll(" ", "+").split(",")[1];
        String url = faceConfig.getImgContrasturl();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            Map<String, Object> map = new HashMap<>();
            map.put("file", base64Image);

            ObjectMapper mapper = new ObjectMapper();
            StringEntity params = new StringEntity(mapper.writeValueAsString(map), StandardCharsets.UTF_8);
            httpPost.addHeader(faceConfig.getContent_Type(), faceConfig.getContent_Type_Value());
            httpPost.addHeader(faceConfig.getX_api_key(), faceConfig.getImgContrastkey());
            httpPost.setEntity(params);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                org.apache.http.HttpEntity entity = response.getEntity();
                String jsonResponse = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                // 使用ObjectMapper解析JSON响应到FaceDetectionResponse2对象
                FaceDetectionResponse2 faceDetectionResponse2 = mapper.readValue(jsonResponse, FaceDetectionResponse2.class);

                // 这里可以添加对faceDetectionResponse2的处理逻辑
                // 例如：打印结果或返回给调用者
                return faceDetectionResponse2;
            }
        } catch (IOException e) {
            throw new IOException("Error processing HTTP request or parsing JSON response", e);
        }
    }

    @Override
    public String defenseface(String imageBase64, String subject) throws IOException {
        // 调用创建任务名称的方法
        String baseUrl = faceConfig.getBk_baseUrl();
        String methodAddr = faceConfig.getDefensefaceAddr();
        String url = baseUrl + methodAddr;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("X-Api-Key", faceConfig.getImgContrastkey());

        // 假设 subjectData 是一个 JSON 字符串，包含了您要添加的 subject 的数据
        // 您需要根据 API 的具体要求来构造这个 JSON 字符串
        String subjectJson = "{\"subject\": \"" + subject + "\"}";

        HttpEntity<String> entity = new HttpEntity<>(subjectJson, headers);

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String responseBody = responseEntity.getBody();
            log.info("添加操作成功，结果为：" + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加操作异常：" + e.getMessage());
        }

        // 创建JSON对象映射器
        ObjectMapper mapper = new ObjectMapper();

        // 创建请求体Map，包含键值对："file" -> imageBase64
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("file", imageBase64);

        // 将请求体序列化为JSON格式的字符串
        String jsonRequest = mapper.writeValueAsString(requestBody);

        // 构建API URL，其中SUBJECT_NAME需要在外部定义
        String apiUrl = faceConfig.getDefenseApiUrl()+ subject;

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建HttpPost对象，设置URL
            HttpPost post = new HttpPost(apiUrl);

            // 设置请求头信息
            post.setHeader(faceConfig.getContent_Type(), faceConfig.getContent_Type_Value());
            post.setHeader(faceConfig.getX_api_key(), faceConfig.getImgContrastkey());

            // 设置请求体，将JSON字符串作为请求的实体
            post.setEntity(new StringEntity(jsonRequest, StandardCharsets.UTF_8));

            // 执行POST请求，并捕获响应
            try (CloseableHttpResponse response = client.execute(post)) {
                // 将响应实体转换为字符串
                String responseString = null;
                try {
                    responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                // 打印响应内容
                System.out.println(responseString);

                // 返回响应字符串
                return responseString;
            }
        }
    }
}


